package com.idanchuang.component.shadow.route.common.filter;


import com.idanchuang.component.core.helper.EnvContext;
import com.idanchuang.component.shadow.route.common.conf.ShadowRouteProperties;
import com.idanchuang.component.shadow.route.common.context.ShadowRouteContext;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter(urlPatterns = "/*", asyncSupported = true)
public class ShadowRouteDataSourceFilter implements Filter {

    private final ShadowRouteProperties properties;

    public ShadowRouteDataSourceFilter(ShadowRouteProperties properties) {
        this.properties = properties;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // NO-OP
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        try {
            String headerValue = ((HttpServletRequest) request).getHeader(EnvContext.getEnvHeaderName());
            if (headerValue != null) {
                ShadowRouteContext.setRoutingKey(properties.getShadowDataSourceName());
            } else {
                ShadowRouteContext.setRoutingKey(properties.getActualDataSourceName());
            }
            chain.doFilter(request, response);
        } finally {
            ShadowRouteContext.reset();
        }
    }

    @Override
    public void destroy() {
        // NO-OP
    }

}
